package com.dalongxin.work.page;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.dalongxin.work.Constants;
import com.dalongxin.work.EventCenter;
import com.dalongxin.work.R;
import com.dalongxin.work.data.Buy;
import com.dalongxin.work.data.Company;
import com.dalongxin.work.data.Contact;
import com.dalongxin.work.data.Project;
import com.dalongxin.work.utils.HttpUtil;
import com.dalongxin.work.utils.StatusBarUtil;
import com.dalongxin.work.utils.ToastUtil;
import com.dalongxin.work.view.MyCommonEditDialog;
import com.dalongxin.work.view.MyCommonDialog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新建采购计划
 */
@ContentView(R.layout.activity_dj_new_buy)
public class DjBuyNewActivity extends BaseActivity implements View.OnClickListener {

    @ViewInject(R.id.tool_bar)
    private Toolbar toolbar;
    @ViewInject(R.id.title_back)
    private ImageButton titleBack;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.submit)
    private TextView submit;

    @ViewInject(R.id.tv_choose_company)
    private TextView tvChooseCompany;//选择公司
    @ViewInject(R.id.tv_choose_shr)
    private TextView tvChooseShr;//选择审核人
    @ViewInject(R.id.tv_choose_pzr)
    private TextView tvChoosePzr;//选择批准人

    @ViewInject(R.id.tv_choose_sqrq)
    private TextView tvChooseSqrq;//申请日期
    @ViewInject(R.id.tv_add_goods)
    private TextView tvAddGoods;//添加采购物品清单
    @ViewInject(R.id.layout_good_list)
    private LinearLayout layoutGoodList;//采购物品清单列表
    @ViewInject(R.id.tv_add_goods_note)
    private TextView tvAddGoodsNote;
    @ViewInject(R.id.tv_choose_xm)
    private TextView tvChooseXm;//选择项目
    @ViewInject(R.id.et_yt)
    private EditText etYt;//用途
    @ViewInject(R.id.et_hjje)
    private EditText etHjje;//合计金额
    @ViewInject(R.id.et_hjsl)
    private EditText etHjsl;//合计数量
    @ViewInject(R.id.et_hjdj)
    private EditText etHjdj;//合计单价
    @ViewInject(R.id.btn_operate)
    private Button btnOperate;

    public static final int REQ_CHOOSE_COMPANY = 1001;
    public static final int REQ_CHOOSE_CONTACT_SHR = 1002;
    public static final int REQ_CHOOSE_CONTACT_PZR = 1003;
    public static final int REQ_CHOOSE_XM = 1004;
    public Calendar calendar;

    private Company chooseCompany;
    private Contact chooseShr;
    private Contact choosePzr;
    private String sqrq;
    private Project chooseProject;

    private List<Buy.Good> goodsList = new ArrayList<>();
    private String yt;//用途
    private String hjje;//合计金额
    private String hjsl;//合计数量
    private String hjdj;//合计单价

    private MyCommonDialog commonDialog;
    private MyCommonEditDialog commonEditDialog;

    public static final String IS_EDIT = "is_edit";
    private int isEdit = 0;// 0新建 1查看
    private Buy bean;
    private boolean canEdit = false;
    private int editState = 0;//0查看状态 1修改状态

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        //this.setSupportActionBar(toolbar);//这样menu才能显示出来【自定义toolbar的话 这个不要设置】
        //getSupportActionBar().setDisplayShowTitleEnabled(false);//去掉默认title的显示
        StatusBarUtil.setPaddingSmart(this, toolbar);
        StatusBarUtil.darkMode(this, false);
        isEdit = getIntent().getIntExtra(IS_EDIT, 0);
        if(isEdit == 0) {
            titleText.setText("新建采购计划");
            submit.setText("提交");
            switchToEditState();
        }else {
            Bundle bundle = getIntent().getBundleExtra("bundle");
            bean = (Buy) bundle.getSerializable("BEAN");
            if(bean == null) {
                finish();
                return;
            }
            if(bean.getCreateId() == getDefaultAccount().getId() && bean.getStatus() == 0) {
                canEdit = true;
                titleText.setText("查看采购计划");
                submit.setText("修改");
            }else {
                titleText.setText("查看采购计划");
                submit.setVisibility(View.GONE);
            }
            fillDataToPage(bean);
            btnOperate.setVisibility(showOperateBtn(bean) ? View.VISIBLE : View.GONE);
            btnOperate.setOnClickListener(this);
        }
        titleBack.setOnClickListener(this);
        submit.setOnClickListener(this);

        calendar = Calendar.getInstance();
    }

    private boolean showOperateBtn(Buy bean) {
        if(bean.getStatus() == 0 && bean.getApproveId1() == getDefaultAccount().getId()) {
            return true;
        }
        if(bean.getStatus() == 1 && bean.getApproveId2() == getDefaultAccount().getId()) {
            return true;
        }
        return false;
    }

    private void fillDataToPage(Buy bean) {
        chooseCompany = new Company();
        chooseCompany.setId(bean.getCompanyId());
        chooseCompany.setName(bean.getCompanyName());
        chooseProject = new Project();
        chooseProject.setId(bean.getProjectId());
        chooseProject.setName(bean.getProjectName());
        chooseShr = new Contact();
        chooseShr.setId(bean.getApproveId1());
        chooseShr.setUserName(bean.getApproveName1());
        choosePzr = new Contact();
        choosePzr.setId(bean.getApproveId2());
        choosePzr.setUserName(bean.getApproveName2());

        hjje = String.valueOf(bean.getTotalFee());
        hjsl = String.valueOf(bean.getTotalNum());
        hjdj = String.valueOf(bean.getTotalPrice());
        sqrq = bean.getFillDate();
        yt = bean.getRemark();

        tvChooseCompany.setText(chooseCompany.getName());
        tvChooseXm.setText(chooseProject.getName());
        tvChooseShr.setText(chooseShr.getUserName());
        tvChoosePzr.setText(choosePzr.getUserName());
        tvChooseSqrq.setText(sqrq);

        etHjje.setText(hjje);
        etHjsl.setText(hjsl);
        etHjdj.setText(hjdj);
        etYt.setText(yt);

        goodsList = bean.getGoodsList();
        if(goodsList != null && goodsList.size() > 0) {
            tvAddGoodsNote.setVisibility(View.GONE);
            for(Buy.Good good : goodsList) {
                TextView tv = new TextView(DjBuyNewActivity.this);
                tv.setText("[材料名称]：" + good.getGoodsName() + " [材料数量]:" + good.getGoodsNum()
                        + " [材料单价]:" + good.getGoodsPrice() + " [材料总价]:" + good.getGoodsFee());
                layoutGoodList.addView(tv);
            }
        }else {
            tvAddGoodsNote.setVisibility(View.GONE);
        }
        switchToViewState();//默认查看状态
    }

    private void switchToEditState() {
        tvChooseCompany.setOnClickListener(this);
        tvChooseShr.setOnClickListener(this);
        tvChoosePzr.setOnClickListener(this);
        tvChooseSqrq.setOnClickListener(this);
        tvChooseXm.setOnClickListener(this);
        if(isEdit == 0) {
            tvAddGoods.setOnClickListener(this);
            tvAddGoods.setVisibility(View.VISIBLE);
        }else {
            tvAddGoods.setOnClickListener(null);
            tvAddGoods.setVisibility(View.GONE);
        }
        etHjje.setEnabled(true);
        etHjsl.setEnabled(true);
        etHjdj.setEnabled(true);
        etYt.setEnabled(true);
    }

    private void switchToViewState() {
        tvChooseCompany.setOnClickListener(null);
        tvChooseShr.setOnClickListener(null);
        tvChoosePzr.setOnClickListener(null);
        tvChooseSqrq.setOnClickListener(null);
        tvChooseXm.setOnClickListener(null);
        tvAddGoods.setOnClickListener(null);
        tvAddGoods.setVisibility(View.GONE);
        etHjje.setEnabled(false);
        etHjsl.setEnabled(false);
        etHjdj.setEnabled(false);
        etYt.setEnabled(false);
    }

    private void submitBuy() {
        showLoading();
        Map<String, String> params = new HashMap<>();
        params.put("approveId1", String.valueOf(chooseShr.getId()));
        params.put("approveId2",String.valueOf(choosePzr.getId()));
        params.put("companyId", String.valueOf(chooseCompany.getId()));
        params.put("jsonData", gson.toJson(goodsList));
        params.put("totalFee", hjje);
        params.put("totalNum", hjsl);
        params.put("totalPrice", hjdj);
        params.put("fillDate", sqrq);
        params.put("projectId", String.valueOf(chooseProject.getId()));
        params.put("remark", yt);
        if(canEdit) {
            params.put("id", String.valueOf(bean.getId()));
        }else {
            params.put("id", String.valueOf(0));
        }
        HttpUtil.getInstance().post(true, Constants.url_saveBuy, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    ToastUtil.showShort("提交成功");
                    EventBus.getDefault().post(EventCenter.call(EventCenter.BUY_REFRESH));
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showShort("服务器返回失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    private void submitApprove(String content, int result) {
        showLoading();
        Map<String, String> params = new HashMap<>();
        params.put("msg", content);
        params.put("result", String.valueOf(result));
        params.put("id", String.valueOf(bean.getId()));
        HttpUtil.getInstance().post(true, Constants.url_approveBuy, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                commonEditDialog.dismiss();
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    ToastUtil.showShort("提交成功");
                    EventBus.getDefault().post(EventCenter.call(EventCenter.BUY_REFRESH));
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showShort("服务器返回失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    private void preSubmit() {
        if(chooseCompany == null) {
            ToastUtil.showShort("请选择公司");
            return;
        }
        if(chooseShr == null) {
            ToastUtil.showShort("请选择审核人");
            return;
        }
        if(choosePzr == null) {
            ToastUtil.showShort("请选择批准人");
            return;
        }
        if(TextUtils.isEmpty(sqrq)) {
            ToastUtil.showShort("请选择申请日期");
            return;
        }
        if(goodsList == null || goodsList.size() == 0) {
            ToastUtil.showShort("至少要添加一种采购物品清单");
            return;
        }
        if(chooseProject == null) {
            ToastUtil.showShort("请选择项目");
            return;
        }
        yt = etYt.getText().toString();
        if(TextUtils.isEmpty(yt)) {
            ToastUtil.showShort("请填写用途");
            return;
        }
        hjje = etHjje.getText().toString();
        if(TextUtils.isEmpty(hjje)) {
            ToastUtil.showShort("请填写合计金额");
            return;
        }
        hjsl = etHjsl.getText().toString();
        if(TextUtils.isEmpty(hjsl)) {
            ToastUtil.showShort("请填写合计数量");
            return;
        }
        hjdj = etHjdj.getText().toString();
        if(TextUtils.isEmpty(hjdj)) {
            ToastUtil.showShort("请填写合计单价");
            return;
        }
        commonDialog = new MyCommonDialog(this, "提示消息", "确定提交吗？", "检查一下","提交");
        commonDialog.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null && commonDialog.isShowing())
                    commonDialog.dismiss();
                submitBuy();
            }
        });
        commonDialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null && commonDialog.isShowing())
                    commonDialog.dismiss();
            }
        });
        commonDialog.show();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.submit:
                if(isEdit == 0) {
                    preSubmit();
                }else {
                    if(canEdit) {
                        if (editState == 0) {
                            editState = 1;
                            titleText.setText("修改采购计划");
                            submit.setText("提交");
                            switchToEditState();
                        } else {
                            editState = 0;
                            titleText.setText("修改采购计划");
                            preSubmit();
                        }
                    }
                }
                break;
            case R.id.tv_choose_sqrq:
                int year2 = calendar.get(Calendar.YEAR);
                int month2 = (calendar.get(Calendar.MONTH))+1;
                int day_of_month2 = calendar.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        sqrq = String.format("%d-%d-%d",i,i1+1,i2);
                        tvChooseSqrq.setText(sqrq);
                        tvChooseSqrq.setTextColor(getResources().getColor(R.color.black));
                    }
                },year2, month2, day_of_month2).show();
                break;
            case R.id.tv_add_goods:
                final MyCommonEditDialog.Builder builder = new MyCommonEditDialog.Builder(this);
                commonEditDialog = builder.view(R.layout.dialog_new_buy_goods).widthdp(300).heightdp(440).style(R.style.MyDialogStyle)
                .addViewOnclick(R.id.cancel, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        commonEditDialog.dismiss();
                    }
                }).addViewOnclick(R.id.ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EditText etClmc = (EditText)builder.findViewById(R.id.et_clmc);
                        EditText etClsm = (EditText)builder.findViewById(R.id.et_clsm);
                        EditText etCldj = (EditText)builder.findViewById(R.id.et_cldj);
                        EditText etClzj = (EditText)builder.findViewById(R.id.et_clzj);
                        String clmc = etClmc.getText().toString();
                        if(TextUtils.isEmpty(clmc)) {
                            ToastUtil.showShort("请填写材料名称");
                            return;
                        }
                        String clsm = etClsm.getText().toString();
                        if(TextUtils.isEmpty(clsm)) {
                            ToastUtil.showShort("请填写材料数目");
                            return;
                        }
                        String cldj = etCldj.getText().toString();
                        if(TextUtils.isEmpty(cldj)) {
                            ToastUtil.showShort("请填写材料单价");
                            return;
                        }
                        String clzj = etClzj.getText().toString();
                        if(TextUtils.isEmpty(clzj)) {
                            ToastUtil.showShort("请填写材料总价");
                            return;
                        }
                        Buy.Good good = new Buy.Good();
                        good.setGoodsName(clmc);
                        good.setGoodsNum(Integer.valueOf(clsm));
                        good.setGoodsPrice(Double.valueOf(cldj));
                        good.setGoodsFee(Double.valueOf(clzj));
                        goodsList.add(good);
                        TextView tv = new TextView(DjBuyNewActivity.this);
                        tv.setText("[材料名称]：" + clmc + " [材料数量]:" + clsm + " [材料单价]:" + cldj + " [材料总价]:" + clzj);
                        tvAddGoodsNote.setVisibility(View.GONE);
                        layoutGoodList.addView(tv);
                        ToastUtil.showShort("添加成功");
                        commonEditDialog.dismiss();
                    }
                }).build();
                commonEditDialog.show();
                break;
            case R.id.tv_choose_company:
                intent = new Intent(this, CompanyListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_COMPANY);
                break;
            case R.id.tv_choose_shr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_SHR);
                break;
            case R.id.tv_choose_pzr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_PZR);
                break;
            case R.id.tv_choose_xm:
                intent = new Intent(this, ProjectListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_XM);
                break;
            case R.id.btn_operate:
                final MyCommonEditDialog.Builder builder2 = new MyCommonEditDialog.Builder(this);
                commonEditDialog = builder2.view(R.layout.dialog_approve).widthdp(300).heightdp(320).style(R.style.MyDialogStyle)
                        .addViewOnclick(R.id.cancel, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                commonEditDialog.dismiss();
                            }
                        }).addViewOnclick(R.id.ok, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                EditText etSpyj = (EditText)builder2.findViewById(R.id.et_spyj);
                                String spyj = etSpyj.getText().toString();
                                if(TextUtils.isEmpty(spyj)) {
                                    spyj = "";
                                }
                                RadioButton yes = (RadioButton)builder2.findViewById(R.id.radio_result_yes);
                                submitApprove(spyj, yes.isChecked() ? 0 : 1);
                            }
                        }).build();
                commonEditDialog.show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null)return;
        if(resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQ_CHOOSE_COMPANY:
                    chooseCompany = (Company)data.getSerializableExtra(CompanyListActivity.DATA_CHOOSE_COMPANY);
                    tvChooseCompany.setText(chooseCompany.getName());
                    tvChooseCompany.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_SHR:
                    //Department department = (Department)data.getSerializableExtra(DepartmentListActivity.DATA_CHOOSE_DEPARTMENT);
                    chooseShr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChooseShr.setText(chooseShr.getUserName());
                    tvChooseShr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_PZR:
                    choosePzr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChoosePzr.setText(choosePzr.getUserName());
                    tvChoosePzr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_XM:
                    chooseProject = (Project)data.getSerializableExtra(ProjectListActivity.DATA_CHOOSE_XM);
                    tvChooseXm.setText(chooseProject.getName());
                    tvChooseXm.setTextColor(getResources().getColor(R.color.black));
                    break;
            }
        }
    }
}
